<script setup>
import { UserLogService } from "@/service/UserLogService";
import { UserService } from "@/service/UserService";
import { BaseService } from "@/service/base";
import { useToast } from "primevue/usetoast";
import { ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const userList = ref(null);
const userLogs = ref();
const dt = ref();
const visibleLeft = ref(false);
const visibleRight = ref(false);
const visibleDetail = ref(false);
const userDialog = ref(false);
const currentLog = ref({});
const user = ref({});
const selectedProducts = ref();
const filters = ref({});
const submitted = ref(false);
const params = ref({
    name: "",
    sn: "",
    tel: "",
    departid: 0,
});

let _toast = null;
const getToast = () => {
    if (!_toast) {
        try {
            _toast = useToast();
        } catch (e) {
            console.warn('PrimeVue Toast 服务不可用:', e.message);
        }
    }
    return _toast;
};

// 错误处理函数
const handleError = (result) => {
    const toast = getToast();
    if (toast) {
        toast.add({
            severity: "error",
            summary: "Error Message",
            detail: result.Title,
            life: 3000,
        });
    } else {
        // 降级处理：使用console输出
        console.error('Toast不可用:', result.Title);
    }
};

const queryUsers = () => {
    params.value.name = params.value.name.trim();
    params.value.sn = params.value.sn.trim();
    params.value.tel = params.value.tel.trim();
    UserService.queryUsers(params.value)
        .then((result) => {
            if (result.Code != 1000) {
                handleError(result);
            } else {
                userList.value = result.Data;
            }
        })
        .catch((error) => {
            handleError({ Title: "查询用户出错", Code: -1 });
        });
};

watch(
    () => route.fullPath,
    () => {
        if (route.params.departid) {
            params.value.departid = route.params.departid;
        }
        queryUsers();
    },
    { immediate: true }
);

const exportCSV = () => {
    if (dt.value) {
        dt.value.exportCSV();
    } else {
        handleError({ Title: "导出 CSV 出错，未找到表格实例", Code: -1 });
    }
};

const openUserHome = (prod) => {
    user.value = { ...prod };
    const url = router.resolve({ path: "/client/" + prod.Sn });
    window.open(url.href, "_blank");
};

const openLog = (prod) => {
    user.value = { ...prod };
    visibleRight.value = true;
    queryUserLogs();
};

const openChat = (prod) => {
    const url = router.resolve({ path: "/chat/" + prod.Sn });
    window.open(url.href, "_blank");
};
const queryUserLogs = () => {
    UserLogService.queryUserLog(user.value.Sn, 0, 1000)
        .then((result) => {
            if (result.Code != 1000) {
                handleError(result);
            } else {
                userLogs.value = result.Data;
            }
        })
        .catch((error) => {
            handleError({ Title: "查询用户日志出错", Code: -1 });
        });
};

const appendLog = () => {
    const fileInput = document.getElementById("screenshot");
    const file = fileInput?.files[0];
    if (file) {
        const formData = new FormData();
        formData.append("file", file);
        BaseService.uploadFile("log", formData)
            .then((result) => {
                if (result.Code !== 1000) {
                    handleError(result);
                } else {
                    currentLog.value.AttachUrl = result.Data;
                    document.getElementById("displayImage").src = "/assets/img.png";
                }
            })
            .catch((error) => {
                console.error("Error uploading file:", error);
                handleError({ Title: "文件上传出错", Code: -1 });
            });
    }

    UserLogService.appendLog(user.value.Sn, currentLog.value)
        .then((result) => {
            if (result.Code !== 1000) {
                handleError(result);
            } else {
                if (!userLogs.value) {
                    userLogs.value = [];
                }
                userLogs.value.push(result.Data);
                currentLog.value.AttachUrl = "";
                currentLog.value.Comments = "";
            }
        })
        .catch((error) => {
            console.error("Error appending log:", error);
            handleError({ Title: "追加日志出错", Code: -1 });
        });
};

const appendLogComment = (thisLog) => {
    UserLogService.appendLogComment(thisLog.Id, thisLog.NewChild)
        .then((result) => {
            if (result.Code != 1000) {
                handleError(result);
            } else {
                if (!thisLog.Children) {
                    thisLog.Children = "[]";
                }
                let temp = JSON.parse(thisLog.Children);
                temp.push(result.Data);
                thisLog.Children = JSON.stringify(temp);
                thisLog.NewChild = "";
                thisLog.relog = false;
            }
        })
        .catch((error) => {
            handleError({ Title: "追加日志评论出错", Code: -1 });
        });
};

const parseChildren = (children) => {
    if (children) {
        try {
            return JSON.parse(children);
        } catch (error) {
            handleError({ Title: "解析子元素出错", Code: -1 });
            return null;
        }
    }
    return null;
};

const onUploadImage = (e) => {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (event) {
            const displayImage = document.getElementById("displayImage");
            if (displayImage) {
                displayImage.src = event.target.result;
            } else {
                handleError({ Title: "未找到显示图片元素", Code: -1 });
            }
        };
        reader.readAsDataURL(file);
    }
};

const openAnalysis = (data) => {
    const url = `/userAnalysis/${data.Sn}`;
    const newWindow = window.open(url, "_blank");
    if (newWindow) {
        newWindow.opener = null;
    }
};

</script>

<template>
    <div class="card rounded-xl shadow-md">
        <Toolbar class="mb-6 rounded-lg bg-gradient-to-r from-blue-50 to-indigo-50 p-4">
            <template #start>
                <!-- <span>用户列表</span> -->
            </template>
            <template #end>
                <span class="font-medium text-gray-700 mr-2">搜索：</span>
                <div class="flex gap-2 flex-wrap">
                    <div class="relative">
                        <InputText type="text" placeholder="姓名"
                            class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            v-model="params.name" />
                        <i class="pi pi-user absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div class="relative">
                        <InputText type="text" placeholder="学号"
                            class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            v-model="params.sn" />
                        <i class="pi pi-id-card absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <div class="relative">
                        <InputText type="text" placeholder="电话"
                            class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            v-model="params.tel" />
                        <i class="pi pi-phone absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <Button label="搜索" icon="pi pi-search" @click="queryUsers"
                        class="bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 shadow hover:shadow-md">
                    </Button>
                    <Button label="导出" icon="pi pi-download" severity="secondary" @click="exportCSV($event)"
                        class="bg-gradient-to-r from-green-500 to-teal-600 hover:from-green-600 hover:to-teal-700 text-white font-medium py-2 px-6 rounded-lg transition-all duration-300 shadow hover:shadow-md">
                    </Button>
                </div>
            </template>
        </Toolbar>

        <DataTable ref="dt" v-model:selection="selectedProducts" :value="userList" dataKey="Sn" :paginator="true"
            :rows="100" :filters="filters"
            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            :rowsPerPageOptions="[50, 100, 200]" currentPageReportTemplate="第 {first} - {last} 条. 总{totalRecords}条. 每页"
            class="rounded-xl overflow-hidden shadow-sm border border-gray-200" sortMode="single" sortField="Sn">

            <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>

            <Column field="Sn" header="学号" sortable style="min-width: 7rem">
                <template #body="slotProps">
                    <span class="font-medium text-gray-900 bg-gray-100 px-3 py-1 rounded-full text-sm">
                        {{ slotProps.data.Sn }}
                    </span>
                </template>
            </Column>

            <Column field="Name" header="姓名" style="min-width: 8rem">
                <template #body="slotProps">
                    <a :href="'/client/' + slotProps.data.Sn + '/profile'" target="_blank" class="no-underline">
                        <span class="text-green-600 hover:text-green-800 font-medium flex items-center">
                            <i class="pi pi-user mr-2"></i>
                            {{ slotProps.data.Name }}
                        </span>
                    </a>
                </template>
            </Column>

            <Column field="Sex" header="性别" style="min-width: 5rem">
                <template #body="slotProps">
                    <span :class="[
                        'px-3 py-1 rounded-full text-xs font-medium',
                        slotProps.data.Sex === '男' ? 'bg-blue-100 text-green-800' : 'bg-pink-100 text-pink-800'
                    ]">
                        {{ slotProps.data.Sex }}
                    </span>
                </template>
            </Column>

            <Column field="Tel" header="电话" style="min-width: 8rem">
                <template #body="slotProps">
                    <span class="text-gray-600 flex items-center">
                        <i class="pi pi-phone mr-2 text-gray-400"></i>
                        {{ slotProps.data.Tel }}
                    </span>
                </template>
            </Column>

            <Column field="Status" header="访谈状态" style="min-width: 5rem">
                <template #body="slotProps">
                    <Button icon="pi pi-book" severity="info"
                        v-if="new Date(slotProps.data.LastFillAnswerTime).getTime() > 0"
                        :label="slotProps.data.LastFillAnswerTemplate" :title="slotProps.data.LastFillAnswerTime"
                        class="mr-2 rounded-full hover:scale-105 transition-transform"
                        @click="openAnalysis(slotProps.data)" />
                    <span v-else class="text-gray-400 italic">暂无记录</span>
                </template>
            </Column>

            <Column header="操作" style="min-width: 12rem; text-align: right">
                <template #body="slotProps">
                    <div class="flex justify-end gap-1">
                        <Button icon="pi pi-user" label="主页" size="small"
                            class="p-button-outlined mr-1 rounded-lg hover:scale-105 transition-transform"
                            @click="openUserHome(slotProps.data)" />
                        <Button icon="pi pi-pencil" severity="help" label="跟进" size="small"
                            class="p-button-outlined mr-1 rounded-lg hover:scale-105 transition-transform"
                            @click="openLog(slotProps.data)" />
                        <Button icon="pi pi-heart" severity="warn" label="访谈" size="small"
                            class="p-button-outlined rounded-lg hover:scale-105 transition-transform"
                            @click="openChat(slotProps.data)" />
                    </div>
                </template>
            </Column>
        </DataTable>
    </div>

    <Dialog v-model:visible="visibleLeft" :style="{ width: '450px' }" header="用户详情" :modal="true" class="p-fluid">
        <div class="field">
            <label for="name">姓名</label>
            <InputText id="name" v-model="user.Name" required="true" autofocus
                :class="{ 'p-invalid': submitted && !user.Name }" />
            <small class="p-error" v-if="submitted && !user.Name">姓名不能为空。</small>
        </div>
        <div class="field">
            <label for="sex">性别</label>
            <Dropdown id="sex" v-model="user.Sex" :options="['男', '女']" placeholder="选择性别" />
        </div>
        <div class="field">
            <label for="tel">电话</label>
            <InputText id="tel" v-model="user.Tel" required="true" :class="{ 'p-invalid': submitted && !user.Tel }" />
            <small class="p-error" v-if="submitted && !user.Tel">电话不能为空。</small>
        </div>
        <div class="field">
            <label for="email">邮箱</label>
            <InputText id="email" v-model="user.Email" required="true"
                :class="{ 'p-invalid': submitted && !user.Email }" />
            <small class="p-error" v-if="submitted && !user.Email">邮箱不能为空。</small>
        </div>
        <div class="field">
            <label for="address">地址</label>
            <InputText id="address" v-model="user.Address" required="true"
                :class="{ 'p-invalid': submitted && !user.Address }" />
            <small class="p-error" v-if="submitted && !user.Address">地址不能为空。</small>
        </div>
        <div class="field">
            <label for="birthday">生日</label>
            <Calendar id="birthday" v-model="user.Birthday" dateFormat="yy-mm-dd" />
        </div>
        <div class="field">
            <label for="department">部门</label>
            <Dropdown id="department" v-model="user.Department" :options="['研发部', '市场部', '销售部']" placeholder="选择部门" />
        </div>
        <div class="field">
            <label for="position">职位</label>
            <InputText id="position" v-model="user.Position" required="true"
                :class="{ 'p-invalid': submitted && !user.Position }" />
            <small class="p-error" v-if="submitted && !user.Position">职位不能为空。</small>
        </div>
        <div class="field">
            <label for="status">状态</label>
            <Dropdown id="status" v-model="user.Status" :options="['活跃', '停用']" placeholder="选择状态" />
        </div>
        <div class="field">
            <label for="notes">备注</label>
            <Textarea id="notes" v-model="user.Notes" rows="4" cols="20" />
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="保存" icon="pi pi-check" class="p-button-text" @click="saveUser" />
        </template>
    </Dialog>

    <Dialog v-model:visible="visibleRight" :style="{ width: '450px' }" header="用户日志" :modal="true" class="p-fluid">
        <div class="field">
            <label for="comments">日志内容</label>
            <Textarea id="comments" v-model="currentLog.Comments" rows="4" cols="20" />
        </div>
        <div class="field">
            <label for="screenshot">截图</label>
            <FileUpload id="screenshot" mode="basic" name="demo[]" accept="image/*" :maxFileSize="1000000"
                @change="onUploadImage" />
            <img id="displayImage" src="../assets/img.png" alt="screenshot" width="150" />
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="保存" icon="pi pi-check" class="p-button-text" @click="appendLog" />
        </template>
    </Dialog>

    <Dialog v-model:visible="visibleDetail" :style="{ width: '450px' }" header="日志详情" :modal="true" class="p-fluid">
        <div class="field">
            <label for="comments">日志内容</label>
            <Textarea id="comments" v-model="currentLog.Comments" rows="4" cols="20" />
        </div>
        <div class="field">
            <label for="screenshot">截图</label>
            <img id="displayImage" :src="currentLog.AttachUrl || '../assets/img.png'" alt="screenshot" width="150" />
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="保存" icon="pi pi-check" class="p-button-text" @click="appendLog" />
        </template>
    </Dialog>

    <Dialog v-model:visible="userDialog" :style="{ width: '450px' }" header="用户详情" :modal="true" class="p-fluid">
        <div class="field">
            <label for="name">姓名</label>
            <InputText id="name" v-model="user.Name" required="true" autofocus
                :class="{ 'p-invalid': submitted && !user.Name }" />
            <small class="p-error" v-if="submitted && !user.Name">姓名不能为空。</small>
        </div>
        <div class="field">
            <label for="sex">性别</label>
            <Dropdown id="sex" v-model="user.Sex" :options="['男', '女']" placeholder="选择性别" />
        </div>
        <div class="field">
            <label for="tel">电话</label>
            <InputText id="tel" v-model="user.Tel" required="true" :class="{ 'p-invalid': submitted && !user.Tel }" />
            <small class="p-error" v-if="submitted && !user.Tel">电话不能为空。</small>
        </div>
        <div class="field">
            <label for="email">邮箱</label>
            <InputText id="email" v-model="user.Email" required="true"
                :class="{ 'p-invalid': submitted && !user.Email }" />
            <small class="p-error" v-if="submitted && !user.Email">邮箱不能为空。</small>
        </div>
        <div class="field">
            <label for="address">地址</label>
            <InputText id="address" v-model="user.Address" required="true"
                :class="{ 'p-invalid': submitted && !user.Address }" />
            <small class="p-error" v-if="submitted && !user.Address">地址不能为空。</small>
        </div>
        <div class="field">
            <label for="birthday">生日</label>
            <Calendar id="birthday" v-model="user.Birthday" dateFormat="yy-mm-dd" />
        </div>
        <div class="field">
            <label for="department">部门</label>
            <Dropdown id="department" v-model="user.Department" :options="['研发部', '市场部', '销售部']" placeholder="选择部门" />
        </div>
        <div class="field">
            <label for="position">职位</label>
            <InputText id="position" v-model="user.Position" required="true"
                :class="{ 'p-invalid': submitted && !user.Position }" />
            <small class="p-error" v-if="submitted && !user.Position">职位不能为空。</small>
        </div>
        <div class="field">
            <label for="status">状态</label>
            <Dropdown id="status" v-model="user.Status" :options="['活跃', '停用']" placeholder="选择状态" />
        </div>
        <div class="field">
            <label for="notes">备注</label>
            <Textarea id="notes" v-model="user.Notes" rows="4" cols="20" />
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
            <Button label="保存" icon="pi pi-check" class="p-button-text" @click="saveUser" />
        </template>
    </Dialog>

</template>
